package com.ljf.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljf.admin.POJO.SysMenu;
import com.ljf.admin.POJO.VO.TableDataObject;
import com.ljf.admin.service.SysMenuService;
import com.ljf.framework.util.tree.TreeObject;
import com.ljf.framework.util.tree.TreeUtil;
import com.ljf.framework.result.JsonResult;
import com.ljf.framework.security.LjfSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: lijinfeng
 * @Date: 2022/5/10
 * @Description 描述:
 */
@RestController
@RequestMapping("/system/menu")
public class MenuController {
    @Autowired
    private SysMenuService sysMenuService;

    @RequestMapping("/tree")
    public JsonResult getMenuTree(){
        List<SysMenu> list = sysMenuService.list();
        List<TreeObject> tree = TreeUtil.getTree(list);

        return JsonResult.success(tree);
    }

    @GetMapping("list")
    public JsonResult getMenuList(Long currentPage, Long pageSize){
        Page<SysMenu> page = new Page<>(currentPage,pageSize);
        Page<SysMenu> userPage = sysMenuService.page(page);
        long total = userPage.getTotal();
        List<SysMenu> menuList = userPage.getRecords();
        return JsonResult.success(new TableDataObject(menuList,total));
    }

    @GetMapping("list/byUser")
    public JsonResult getMenuList(){
        Long userId = LjfSecurityManager.getUserId();
        List<SysMenu> menuList = null ;
        // 管理员获取所有菜单
        if (1l == userId){
            menuList = sysMenuService.list();
        }else {
            menuList = sysMenuService.getListByUserId(userId);

        }
        List<TreeObject> tree = TreeUtil.getTree(menuList);
        return JsonResult.success(tree);
    }

    @PutMapping
    public JsonResult updateMenu(@RequestBody SysMenu sysMenu){
        boolean save = sysMenuService.saveOrUpdate(sysMenu);
        if(save)
            return JsonResult.success("修改菜单成功");
        return JsonResult.error("修改菜单失败");
    }

    @DeleteMapping("/{menuId}")
    public JsonResult deleteMenuByUser( @PathVariable Long menuId){
        Long userId =  LjfSecurityManager.getUserId();
        if( 1060L < menuId ) {
            sysMenuService.deleteMenuByUser(menuId,userId);
            return JsonResult.success("删除菜单成功");
        }
        return JsonResult.error("原始菜单，不可以删");
    }

    @PostMapping("/{parentId}")
    public JsonResult addMenu(@PathVariable Long parentId, @RequestBody SysMenu sysMenu){
        System.out.println(sysMenu.toString());
        sysMenu.setParentId(parentId);
        // todo 获取最大顺序号 计算得出当前菜单顺序号 并设置
        sysMenuService.save(sysMenu);
        return JsonResult.success();
    }
}
